package com.manbearpig.todue;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
/**
 * This activity is launched so the user can create a new account
 * @author Andre Giron
 * @version 1.0
 */
public class AddToDueActivity extends Activity {
    
	
	private ToDo_Manager tdm;
	String username;
	int _id;
	/**
	Method that runs when the app is launched for the first time
	@param savedInstanceState the state of the app the last time it was launched
	**/
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addtodolayout);
        tdm = new ToDo_Manager();
        this.username = this.getIntent().getExtras().getString("Username");
        this._id = this.getIntent().getExtras().getInt("_ID");
        Spinner spinner = (Spinner)findViewById(R.id.category_Spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.categories, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        
        if(this._id>0)
        {
        	this.fillParams();
        	findViewById(R.id.completedBox).setEnabled(true);
        	((Button)findViewById(R.id.add_button)).setText("Update");
        }
        
        final Button button = (Button) findViewById(R.id.location_button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	Log.d("Map", "Attempting to execute the mapview");
            	Intent myIntent = new Intent(getApplicationContext(), EnterAddressActivity.class);
        		startActivity(myIntent);
            }
        });

    }
    
    
    public boolean addNewToDo(String cat, Date d, String des, Location l, boolean re, String des_shrt){
    	tdm.setUsername(this.username);
    	tdm.setCategory(cat);
    	tdm.setDate(d);
    	tdm.setDescription(des);
    	tdm.setLocation(l);
    	tdm.setRecurrence(re);
    	tdm.setShort_description(des_shrt);
	    boolean success = tdm.attemptCreateToDo(this);
	    return success;
    }

    
    
    
    
    
    
    
    
    /**
     * This method fills in the fields when editing a todo
     */
    private void fillParams()
    {
    	DatabaseHelper dbh = new DatabaseHelper(this);
    	SQLiteDatabase db = dbh.getReadableDatabase();
    	String sql = "SELECT * FROM Todos WHERE _id=?";
    	String id = ((Integer)this._id).toString();
    	Log.d("ID check",id);
    	db.beginTransaction();
    	Cursor cursor = db.rawQuery(sql, new String[]{id});
    	db.setTransactionSuccessful();
    	db.endTransaction();
    	cursor.moveToFirst();
    	Log.d("Description check",((Integer)cursor.getColumnIndex("Description")).toString());
    	String description = cursor.getString(cursor.getColumnIndexOrThrow("Description"));
    	String short_description = cursor.getString(cursor.getColumnIndex("Short_Description"));
    	String category = cursor.getString(cursor.getColumnIndex("Category"));
    	String location = cursor.getString(cursor.getColumnIndex("Location"));
    	String due_date = cursor.getString(cursor.getColumnIndex("Due_Date"));
    	String completed = cursor.getString(cursor.getColumnIndex("Completed"));
    	int recurrence = cursor.getInt(cursor.getColumnIndex("Recurrence"));
    	
    	db.close();
    	dbh.close();
    	
    	((EditText)findViewById(R.id.task_EditText)).setText(short_description);
    	((EditText)findViewById(R.id.description_EditText)).setText(description);
    	//set the rest of the fields according to what we retrieved above.
    	if(recurrence!=0)
    		((CheckBox)findViewById(R.id.recurrence_CheckBox)).setChecked(true);
    	else
    		((CheckBox)findViewById(R.id.recurrence_CheckBox)).setChecked(false);
    	
    	//take care of spinner
    	int position;
    	if(category.equals("Personal"))
    		position = 0;
    	else if(category.equals("School"))
    		position = 1;
    	else
    		position = 2;
    	((Spinner)findViewById(R.id.category_Spinner)).setSelection(position);
    	
    	//take care of completed
    	if(completed.equals("Completed!"))
    		((CheckBox)findViewById(R.id.completedBox)).setChecked(true);
    	else
    		((CheckBox)findViewById(R.id.completedBox)).setChecked(false);
    	
    	//fill date picker
    	int year = Integer.parseInt(due_date.substring(0,4));
    	int month = Integer.parseInt(due_date.substring(5,7));
    	int day = Integer.parseInt(due_date.substring(8,10));
    	Date date = new Date(year,month,day);
    	Log.d("Year",((Integer)date.getYear()).toString());
    	Log.d("Month",((Integer)date.getMonth()).toString());
    	Log.d("Day",((Integer)day).toString());
    	
    	//bug - fix December on click
    	int dateMonth = date.getMonth()-1;
    	if(dateMonth == -1)
    		dateMonth = 11;
    	((DatePicker)findViewById(R.id.datepicker)).init(date.getYear(), dateMonth, date.getDate(), null);
    	cursor.close();
    }
    
    /**
     * OnClick handler for create account button
     * @param view
     */
    public void saveToDo(View view)
    {
    	tdm.setUsername(this.username);
    	
    	tdm.setCategory((String)((Spinner)findViewById(R.id.category_Spinner)).getSelectedItem());
    	DatePicker dp = (DatePicker)findViewById(R.id.datepicker);
    	tdm.setDate(new Date(dp.getYear() - 1900, dp.getMonth(), dp.getDayOfMonth()));
    	tdm.setDescription(((EditText) findViewById(R.id.description_EditText)).getText().toString());
    	tdm.setLocation(null);
    	tdm.setRecurrence(((CheckBox)findViewById(R.id.recurrence_CheckBox)).isChecked());
    	tdm.setShort_description(((EditText) findViewById(R.id.task_EditText)).getText().toString());
    	CheckBox cb = (CheckBox)findViewById(R.id.completedBox);
    	if(cb.isChecked())
    	{
    		tdm.setCompleted("Completed!");
    	}
    	else
    		tdm.setCompleted("Not Completed");
	    boolean success;
	    if(((Button)findViewById(R.id.add_button)).getText().equals("Save"))
	    	success = tdm.attemptCreateToDo(this);
	    else
	    	success = tdm.attemptEditToDo(this, _id);
	    if(success)
	    {
	    	if(((Button)findViewById(R.id.add_button)).getText().equals("Update"))
	    	{
		    	finish();
		    	Intent myIntent = new Intent(this, ToDoListActivity.class);
			    myIntent.putExtra("Username", this.username);
			    startActivity(myIntent);
	    	}
	    	else
	    		finish();
    	} 		
    }
    
    /**
     * Cancel editing/ creating a todo
     * @param view the required view
     */
    public void cancelToDo(View view)
    {
    	if(((Button)findViewById(R.id.add_button)).getText().equals("Update"))
    	{
	    	this.finish();
	    	Intent myIntent = new Intent(this, ToDoListActivity.class);
		    myIntent.putExtra("Username", this.username);
		    startActivity(myIntent);
    	}
    	else
    		this.finish();
    }
    
    /*
    public void showMap(View view)
    {
    	Log.d("Map", "Attempting to execute the mapview");
    	Intent myIntent = new Intent(getApplicationContext(), HelloGoogleMapsActivity.class);
		startActivity(myIntent);
    }
    */
    
    
    
    
}